<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card primary">
          <div class="stat-header">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <span class="stat-trend up">
              <el-icon><CaretTop /></el-icon>
              12%
            </span>
          </div>
          <div class="stat-body">
            <div class="stat-value">{{ formatNumber(dashboardData.totalUsers) }}</div>
            <div class="stat-label">用户总数</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card success">
          <div class="stat-header">
            <div class="stat-icon">
              <el-icon><OfficeBuilding /></el-icon>
            </div>
            <span class="stat-trend up">
              <el-icon><CaretTop /></el-icon>
              8%
            </span>
          </div>
          <div class="stat-body">
            <div class="stat-value">{{ formatNumber(dashboardData.totalOrganizations) }}</div>
            <div class="stat-label">组织总数</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card warning">
          <div class="stat-header">
            <div class="stat-icon">
              <el-icon><Avatar /></el-icon>
            </div>
            <span class="stat-trend up">
              <el-icon><CaretTop /></el-icon>
              5%
            </span>
          </div>
          <div class="stat-body">
            <div class="stat-value">{{ formatNumber(dashboardData.totalRoles) }}</div>
            <div class="stat-label">角色总数</div>
          </div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card danger">
          <div class="stat-header">
            <div class="stat-icon">
              <el-icon><Bell /></el-icon>
            </div>
            <span class="stat-badge" v-if="dashboardData.unreadNotifications > 0">
              {{ dashboardData.unreadNotifications }}
            </span>
          </div>
          <div class="stat-body">
            <div class="stat-value">{{ formatNumber(dashboardData.unreadNotifications) }}</div>
            <div class="stat-label">未读通知</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 快速统计 -->
    <el-row :gutter="16" class="quick-stats">
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="quick-stat-item">
          <div class="quick-stat-icon primary">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="quick-stat-content">
            <div class="quick-stat-value">{{ formatNumber(dashboardData.todayNewUsers) }}</div>
            <div class="quick-stat-label">今日新增</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="quick-stat-item">
          <div class="quick-stat-icon success">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="quick-stat-content">
            <div class="quick-stat-value">{{ formatNumber(dashboardData.pendingMessages) }}</div>
            <div class="quick-stat-label">待处理消息</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="quick-stat-item">
          <div class="quick-stat-icon warning">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="quick-stat-content">
            <div class="quick-stat-value">{{ formatNumber(dashboardData.systemRunningDays) }}</div>
            <div class="quick-stat-label">运行天数</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="quick-stat-item">
          <div class="quick-stat-icon info">
            <el-icon><Connection /></el-icon>
          </div>
          <div class="quick-stat-content">
            <div class="quick-stat-value">{{ formatNumber(dashboardData.onlineUsers) }}</div>
            <div class="quick-stat-label">在线用户</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表和信息 -->
    <el-row :gutter="16">
      <el-col :xs="24" :lg="16">
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">用户趋势分析</h3>
            <div class="chart-actions">
              <el-radio-group v-model="chartPeriod" size="small">
                <el-radio-button label="7天">最近7天</el-radio-button>
                <el-radio-button label="30天" disabled>最近30天</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div ref="chartRef" class="chart-container"></div>
        </div>
      </el-col>

      <el-col :xs="24" :lg="8">
        <div class="system-info-card">
          <div class="info-header">
            <h3 class="info-title">系统信息</h3>
            <el-tag type="success" size="small">运行中</el-tag>
          </div>
          <div class="info-list">
            <div class="info-item">
              <div class="info-item-label">
                <el-icon><Monitor /></el-icon>
                <span>系统版本</span>
              </div>
              <div class="info-item-value">v1.0.0</div>
            </div>
            <div class="info-item">
              <div class="info-item-label">
                <el-icon><Platform /></el-icon>
                <span>运行环境</span>
              </div>
              <div class="info-item-value">Spring Boot 3.1.5</div>
            </div>
            <div class="info-item">
              <div class="info-item-label">
                <el-icon><Coin /></el-icon>
                <span>数据库</span>
              </div>
              <div class="info-item-value">MySQL 8.0</div>
            </div>
            <div class="info-item">
              <div class="info-item-label">
                <el-icon><Odometer /></el-icon>
                <span>内存使用</span>
              </div>
              <div class="info-item-value">
                <el-progress :percentage="68" :show-text="false" style="width: 80px" />
                <span class="memory-text">68%</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getDashboardData, getUserStatistics } from '@/api/dashboard'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  User, OfficeBuilding, Avatar, Bell, TrendCharts, ChatDotRound, 
  Clock, Connection, Monitor, Platform, Coin, Odometer,
  CaretTop
} from '@element-plus/icons-vue'

const dashboardData = ref({})
const userStatistics = ref([])
const chartRef = ref(null)
const chartPeriod = ref('7天')
let chartInstance = null

// 格式化数字，添加千位分隔符
const formatNumber = (num) => {
  if (!num && num !== 0) return '0'
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    const res = await getDashboardData()
    dashboardData.value = res.data
  } catch (error) {
    ElMessage.error('获取仪表盘数据失败')
  }
}

// 获取用户统计数据
const fetchUserStatistics = async () => {
  try {
    const res = await getUserStatistics()
    userStatistics.value = res.data
    initChart()
  } catch (error) {
    ElMessage.error('获取用户统计数据失败')
  }
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)

  const dates = userStatistics.value.map(item => {
    const date = new Date(item.date)
    return `${date.getMonth() + 1}/${date.getDate()}`
  })
  const counts = userStatistics.value.map(item => item.count)

  const isDark = document.documentElement.classList.contains('dark')
  const textColor = isDark ? '#a0a0a0' : '#666666'
  const lineColor = isDark ? '#2a2a2a' : '#e0e0e0'
  const bgColor = isDark ? 'rgba(64, 158, 255, 0.1)' : 'rgba(64, 158, 255, 0.05)'

  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      backgroundColor: isDark ? 'rgba(0, 0, 0, 0.9)' : 'rgba(255, 255, 255, 0.9)',
      borderColor: isDark ? '#333' : '#ddd',
      textStyle: {
        color: isDark ? '#fff' : '#333'
      },
      formatter: (params) => {
        const param = params[0]
        return `${param.name}<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>新增用户: ${param.value}`
      }
    },
    grid: {
      left: '50',
      right: '30',
      top: '30',
      bottom: '30'
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: lineColor
        }
      },
      axisLabel: {
        color: textColor,
        fontSize: 12
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisLabel: {
        color: textColor,
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: lineColor,
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: counts,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF',
          borderWidth: 2,
          borderColor: '#fff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
          ])
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            color: '#409EFF',
            borderColor: '#fff',
            borderWidth: 3,
            shadowBlur: 10,
            shadowColor: 'rgba(64, 158, 255, 0.5)'
          }
        }
      }
    ]
  }

  chartInstance.setOption(option)

  // 响应式
  const resizeHandler = () => {
    chartInstance?.resize()
  }
  window.addEventListener('resize', resizeHandler)
}

onMounted(() => {
  fetchDashboardData()
  fetchUserStatistics()
})

onUnmounted(() => {
  chartInstance?.dispose()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  min-height: calc(100vh - 140px);
}

/* 统计卡片 */
.stats-row {
  margin-bottom: 16px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  transition: all 0.3s ease;
}

.stat-card.primary::before { background: #409EFF; }
.stat-card.success::before { background: #67C23A; }
.stat-card.warning::before { background: #E6A23C; }
.stat-card.danger::before { background: #F56C6C; }

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  background: #f5f7fa;
  color: #909399;
  transition: all 0.3s ease;
}

.stat-card.primary .stat-icon { background: #ecf5ff; color: #409EFF; }
.stat-card.success .stat-icon { background: #f0f9ff; color: #67C23A; }
.stat-card.warning .stat-icon { background: #fdf6ec; color: #E6A23C; }
.stat-card.danger .stat-icon { background: #fef0f0; color: #F56C6C; }

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  background: #f0f9ff;
  color: #67C23A;
  font-weight: 500;
}

.stat-trend.up { color: #67C23A; background: #f0f9ff; }
.stat-trend.down { color: #F56C6C; background: #fef0f0; }

.stat-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #F56C6C;
  color: #fff;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  font-weight: 500;
}

.stat-body {
  padding-left: 4px;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  font-weight: 400;
}

/* 快速统计 */
.quick-stats {
  margin-bottom: 16px;
}

.quick-stat-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
}

.quick-stat-item:hover {
  border-color: #c0c4cc;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.quick-stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.quick-stat-icon.primary { background: #ecf5ff; color: #409EFF; }
.quick-stat-icon.success { background: #f0f9ff; color: #67C23A; }
.quick-stat-icon.warning { background: #fdf6ec; color: #E6A23C; }
.quick-stat-icon.info { background: #f4f4f5; color: #909399; }

.quick-stat-content {
  flex: 1;
}

.quick-stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.quick-stat-label {
  font-size: 13px;
  color: #909399;
}

/* 图表卡片 */
.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.chart-actions :deep(.el-radio-button__inner) {
  padding: 8px 15px;
}

.chart-container {
  height: 320px;
  width: 100%;
}

/* 系统信息卡片 */
.system-info-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e4e7ed;
  height: calc(100% - 16px);
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.info-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.info-item-label .el-icon {
  font-size: 18px;
  color: #909399;
}

.info-item-value {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.memory-text {
  font-size: 13px;
  color: #606266;
  min-width: 36px;
}

/* 暗黑模式 */
.dark .stat-card,
.dark .quick-stat-item,
.dark .chart-card,
.dark .system-info-card {
  background: #1a1a1a;
  border-color: #2a2a2a;
}

.dark .stat-value,
.dark .quick-stat-value,
.dark .chart-title,
.dark .info-title,
.dark .info-item-value {
  color: #e5e7eb;
}

.dark .stat-label,
.dark .quick-stat-label,
.dark .info-item-label {
  color: #9ca3af;
}

.dark .stat-icon {
  background: #2a2a2a;
  color: #6b7280;
}

.dark .stat-card.primary .stat-icon { background: rgba(64, 158, 255, 0.15); color: #409EFF; }
.dark .stat-card.success .stat-icon { background: rgba(103, 194, 58, 0.15); color: #67C23A; }
.dark .stat-card.warning .stat-icon { background: rgba(230, 162, 60, 0.15); color: #E6A23C; }
.dark .stat-card.danger .stat-icon { background: rgba(245, 108, 108, 0.15); color: #F56C6C; }

.dark .quick-stat-icon.primary { background: rgba(64, 158, 255, 0.15); color: #409EFF; }
.dark .quick-stat-icon.success { background: rgba(103, 194, 58, 0.15); color: #67C23A; }
.dark .quick-stat-icon.warning { background: rgba(230, 162, 60, 0.15); color: #E6A23C; }
.dark .quick-stat-icon.info { background: #2a2a2a; color: #6b7280; }

.dark .stat-trend {
  background: rgba(64, 158, 255, 0.15);
}

.dark .stat-card:hover,
.dark .quick-stat-item:hover,
.dark .chart-card:hover,
.dark .system-info-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

.dark .info-item {
  border-bottom-color: #2a2a2a;
}

.dark .memory-text {
  color: #9ca3af;
}

.dark .quick-stat-item:hover {
  border-color: #3a3a3a;
}

.dark .info-item-label .el-icon {
  color: #6b7280;
}

/* 响应式 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 12px;
  }

  .stat-card,
  .quick-stat-item,
  .chart-card,
  .system-info-card {
    padding: 16px;
  }

  .stat-value {
    font-size: 24px;
  }

  .quick-stat-value {
    font-size: 18px;
  }

  .chart-container {
    height: 260px;
  }

  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>

